package com.silverhaze.aurora.web;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.MessageDigest;

/**
 * This code is part of Kg.Axion project. Treat it as strictly confidential.
 * Created by Ivan Babanin.
 * Creation date: 4/7/11 3:02 PM
 */
public class Updater extends HttpServlet {

    private static final int BUFFER_SIZE = 1024;

    private static final String DATA_DIR = System.getProperty("jboss.server.data.dir") + "\\";
    private static final String UPDATER_DATA_DIR = DATA_DIR + "updater\\";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletOutputStream outputStream = response.getOutputStream();

        String fileName = request.getParameter("fileName");
        if (fileName == null) {
            printUpdaterFileList(outputStream);
        } else {
            sendUpdaterFile(fileName, outputStream);
        }

        outputStream.flush();
    }

    private void printUpdaterFileList(ServletOutputStream outputStream) {
        File updaterDir = new File(UPDATER_DATA_DIR);
        PrintWriter writer = new PrintWriter(outputStream);

        if (updaterDir.isDirectory()) {
            File[] files = updaterDir.listFiles();

            for (File file : files) {
                writer.write(file.getAbsolutePath().substring(UPDATER_DATA_DIR.length()) +
                        "\t" + getMD5Checksum(file) + "\t" + file.length() + "\n");
            }
        }

        writer.flush();
    }

    private void sendUpdaterFile(String fileName, ServletOutputStream outputStream) {
        File file = new File(UPDATER_DATA_DIR + fileName);

        try {
            int readByteSize = 0;
            byte[] buffer = new byte[BUFFER_SIZE];
            FileInputStream inputStream = new FileInputStream(file);

            while ((readByteSize = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, readByteSize);
            }

            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] createChecksum(File file) throws Exception {
        InputStream fis = new FileInputStream(file);

        int numRead;
        byte[] buffer = new byte[1024];
        MessageDigest complete = MessageDigest.getInstance("MD5");

        do {
            numRead = fis.read(buffer);

            if (numRead > 0) {
                complete.update(buffer, 0, numRead);
            }
        } while (numRead != -1);

        fis.close();

        return complete.digest();
    }

    public static String getMD5Checksum(File file) {
        StringBuilder result = new StringBuilder();

        try {
            byte[] b = createChecksum(file);

            for (int i = 0; i < b.length; i++) {
                result.append(Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result.toString();
    }
}
